// pages/new-data/index.js
import {
  request
} from '../../api/index'
import {
  fillAll
} from '../../utils/util'
import {
  EMBRY_POWDER_SPRAYING,
  hasErr,
  inputValidHandle
} from '../../utils/valid'

const app = getApp();
const form = {

  ballGrindingFineness: {
    name: 'M1',
    type: '球磨细度',
    value: '',
    err: '',
    desc: EMBRY_POWDER_SPRAYING['ballGrindingFineness'].unit
  },
  mudFlowRate: {
    name: 'M2',
    type: '泥浆流速',
    value: '',
    err: '',
    desc: EMBRY_POWDER_SPRAYING['mudFlowRate'].unit
  },
  mudSpecificGravity: {
    name: 'M3',
    type: '泥浆比重',
    value: '',
    err: '',
    desc: EMBRY_POWDER_SPRAYING['mudSpecificGravity'].unit
  },
  mudComposition: {
    type: '泥浆成分',
    value: '',
    err: ''
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    safeArea: 0,
    form,
    fields: Object.keys(form),
    canNext: false,
    id: '',
    recordState: app.globalData.editState,
    option: [],
    value: undefined,
    show: false,
    btnLoad: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.setPageProperty(options);
    // await this.fetchMenuData();
    if (options.id) {
      this.fetchData();
    }
  },

  /**
   * 设置页面属性
   */
  setPageProperty(options) {
    wx.setNavigationBarTitle({
      title: '1-坯体球磨'
    })
    this.setData({
      id: options.id,
      fromNavigation: options.navigation || 0,
      recordState: app.globalData.editState
    })
  },
  onChange(e) {

    if (!!!this.data.value) {
      wx.showModal({
        showCancel: false,
        title: '未填写泥浆成分'
      })
      return
    }

    if (hasErr(this.data.form)) {
      wx.showToast({
        title: '存在不合理的数值',
        icon: 'none'
      })
      return
    }
    fillAll(e.detail.value, true) &&
      request.ballMillingAdd(Object.assign({
        collectionRecordId: this.data.id,
        mudComposition: this.data.value
      }, e.detail.value, {
        id: this.data.form.id
      }), this.nextHandle)
  },
  /**
   * 选择泥浆成分
   */
  onSelect(event) {
    const value = event.detail;
    this.setData({
      value
    })
  },
  /**
   * 查询泥浆成分可选项
   */
  async fetchMenuData() {
    return new Promise((resolve, reject) => {
      request.getSingleSetting({
        settingKey: 'MUD_COMPOSITION'
      }, res => {
        const {
          settingData
        } = res;
        const arr = settingData?.map(it => {
          return {
            ...it,
            value: it['key'],
            text: `${it['key']}`
          }
        })

        this.setData({
          option: arr,
          value: arr[0]?.value
        })

        resolve();
      }, reject)
    })
  },
  fetchData() {
    request.ballMillingList({
      collectionRecordIds: this.data.id
    }, (e) => {
      let k = Object.assign({}, this.data.form);
      e[0] && this.data.fields.forEach(item => {
        k[item].value = e[0][item],
          k.id = e[0].id
      })
      this.setData({
        form: k,
        value: e[0]?.mudComposition || this.data.value
      })
    })
  },
  nextHandle() {
    if (this.data.fromNavigation > 0) {
      wx.navigateBack({
        delta: 1
      })
      return
    }
    wx.redirectTo({
      url: '../dusting/index?id=' + this.data.id + '&prev=' + route + '&params=' + params,
    })
  },
  toHome() {
    wx.navigateBack({
      delta: 3
    })
  },
  onMudCompositionHide() {
    this.setData({
      show: false
    })
  },
  onMudCompositionShow() {
    this.setData({
      show: true
    })
  },
  onMudCompositionChange(event) {
    const value = event.detail;
    this.setData({
      value
    })
    this.onMudCompositionHide();
  },
  onInput(event) {
    const key = event.currentTarget.dataset.key,
      value = event.detail,
      form = this.data.form;
    const target = EMBRY_POWDER_SPRAYING[key];
    if (inputValidHandle(value, EMBRY_POWDER_SPRAYING, key) === false) {
      form[key]['err'] = '数值不正确：' + target.desc;
    } else {
      form[key]['err'] = '';
    }
    form[key]['value'] = String(value);
    this.setData({
      form
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})